package com.example.pei.papa.activity;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.support.annotation.IdRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.ActionBar.LayoutParams;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.pei.papa.tables.UserInfo;
import com.example.pei.papa.dialog.headChooseDialog;
import com.makeramen.roundedimageview.RoundedImageView;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;


import com.example.pei.papa.R;

import static com.example.pei.papa.utils.PictureUtil.compressBmpToFile;
import static com.example.pei.papa.utils.PictureUtil.compressImageFromFile;


public class register_step_four_Activity extends AppCompatActivity implements View.OnClickListener,View.OnTouchListener ,RadioGroup.OnCheckedChangeListener{

    private Button button_submit;
    private RoundedImageView roundImageHead; //压缩后的圆形头像

    private RadioButton radioButton_female;
    private RadioButton radioButton_male;
    private RadioGroup  radioGroup_sex;

    private ProgressBar progressBar_register;


    private NumberPicker yearNumberPicker;
    private NumberPicker monthNumberPicker;
    private NumberPicker dateNumberPicker;

    private Uri imageUri;
    private File outputImage;       //相机拍摄图片的文件

    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int CROP_REQUEST_CODE = 3;

    private Bitmap cropHeadBitmap;
    //头像在本地的存储路径
    private String headPath;
    //头像在服务器上的url地址
    private String headFileUrl;

    private headChooseDialog dialog;

    private String phone;
    private String userName;
    private String passWord;
    private int sex;//0女 1男

    private int birthYear;
    private int birthMonth;
    private int birthDate;
    private int age;
    private  BmobFile bmobFile;  //头像

    private TextView textView_birth;
    private Button button_select_birth;

    private boolean falgHead; //如果头像已经选择了
    private boolean flagSex;
    private boolean flagBirth;

    private UserInfo userinfo;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_step_four_);

        //////////////////////////////////////////////
        InitView();
        sex=3;  //未选择
        age=200;//未选择
        falgHead=false;
        flagBirth=false;
        flagSex=false;
        birthYear=1996;
        birthMonth=12;
        birthDate=14;
        Intent intent=getIntent();
        phone=intent.getStringExtra("phoneString");
        userName=intent.getStringExtra("userNameString");
        passWord=intent.getStringExtra("passWordString");

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_submit:
                if(headPath==null||cropHeadBitmap==null){
                    Toast.makeText(register_step_four_Activity.this,"请设置头像",Toast.LENGTH_SHORT).show();
                }else if(sex==3) {
                    Toast.makeText(register_step_four_Activity.this,"请设置性别",Toast.LENGTH_SHORT).show();
                }else if(age==200) {
                    Toast.makeText(register_step_four_Activity.this,"请设置年龄",Toast.LENGTH_SHORT).show();
                }else{

                    progressBar_register.setVisibility(View.VISIBLE);//设置可见
                    button_submit.setClickable(false); //设置不可点击注册

                    Bitmap bitmap = BitmapFactory.decodeFile(headPath);
                    File file=new File(getExternalCacheDir(),"HeadImage"+phone+".jpg");
                    try {
                        if(file.exists()){
                            file.delete();
                        }
                        file.createNewFile();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                    compressBmpToFile(cropHeadBitmap,file);
                    userinfo=new UserInfo();
                    bmobFile = new BmobFile(file);
                    bmobFile.uploadblock(new UploadFileListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
                                //Toast.makeText(register_step_four_Activity.this, "上传图片成功", Toast.LENGTH_SHORT).show();
                                userinfo.setPassword(passWord);//
                                userinfo.setUsername(userName);
                                userinfo.setUserType(1);//设置为普通用户
                                //userinfo.setHeadFile(bmobFile);//设置头像
                                userinfo.setHeadFileUrl(bmobFile.getFileUrl());
                                userinfo.setBirthDay(birthYear+"-"+birthMonth+"-"+birthDate);
                                userinfo.setSex(sex);
                                userinfo.setMobilePhoneNumber(phone);
                                userinfo.signUp(new SaveListener<UserInfo>() {
                                    @Override
                                    public void done(UserInfo userInfo, BmobException e) {
                                        if(e==null){
                                            Toast.makeText(register_step_four_Activity.this, "注册成功", Toast.LENGTH_SHORT).show();
                                            progressBar_register.setVisibility(View.INVISIBLE);
//
                                        }else {
                                            Toast.makeText(register_step_four_Activity.this, "注册失败："+e.getMessage(), Toast.LENGTH_LONG).show();
                                            progressBar_register.setVisibility(View.INVISIBLE);
                                            button_submit.setClickable(true);
                                        }
                                    }
                                });

                            } else {
                                Toast.makeText(register_step_four_Activity.this, "上传失败"+e.getMessage(), Toast.LENGTH_LONG).show();
                                progressBar_register.setVisibility(View.INVISIBLE);
                                button_submit.setClickable(true);
                            }
                        }

                        @Override
                        public void onProgress(Integer value) {
                            super.onProgress(value);
                        }
                    });
                }
                break;

            case R.id.btn_select_birth:
                CreateBirthChoice();
                break;
        }

    }



    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()){
            case R.id.img_roudhead:
                View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog, null);
                dialog = new headChooseDialog(this, R.style.transparentFrameWindowStyle,new headChooseDialog.LeaveMyDialogListener(){
                    @Override
                    public void onClick(View view) {
                        switch (view.getId()){
                            case R.id.btn_c:
                                DialogDismiss();
                                break;
                            case R.id.btn_g:
                                if(ContextCompat.checkSelfPermission(register_step_four_Activity.this,
                                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                                    ActivityCompat.requestPermissions(register_step_four_Activity.this,
                                            new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                                }else{
                                    openAlbum();
                                }
                                DialogDismiss();
                                break;
                            case R.id.btn_t:
                                outputImage=new File(getExternalCacheDir(),"tmpCameraImage"+phone+".jpg");
                                try {
                                    if(outputImage.exists()){
                                        outputImage.delete();
                                    }
                                    outputImage.createNewFile();
                                    headPath=outputImage.getPath();
                                }catch (IOException e){
                                    e.printStackTrace();
                                }
                                if(Build.VERSION.SDK_INT>=24){
                                    imageUri= FileProvider.getUriForFile(register_step_four_Activity.this,
                                            "onlyid",outputImage);
                                }else {
                                    imageUri=Uri.fromFile(outputImage);
                                }
                                // 启动相机
                                Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
                                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                                startActivityForResult(intent,CAMERA_REQUEST_CODE);
                                DialogDismiss();
                                break;
                        }
                    }
                });
                dialog.setContentView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
                Window window = dialog.getWindow();
                // 设置显示动画
                window.setWindowAnimations(R.style.main_menu_animstyle);
                WindowManager.LayoutParams wl = window.getAttributes();
                wl.x = 0;
                wl.y = getWindowManager().getDefaultDisplay().getHeight();
                // 以下这两句是为了保证按钮可以水平满屏
                wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
                wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

                // 设置显示位置
                dialog.onWindowAttributesChanged(wl);
                // 设置点击外围解散
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
                break;
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        } else {
            Uri u,s;
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    //判断手机系统版本号
                    if(Build.VERSION.SDK_INT>=19){
                        //4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(data);
                    }else{
                        //4.4及以下系统使用这个方法处理图片
                        handleImageBeforeKitKat(data);
                    }
                    //启动系统裁剪

                    if(Build.VERSION.SDK_INT>=24){
                        u= FileProvider.getUriForFile(register_step_four_Activity.this,
                                "onlyid",new File(headPath));
                    }else {
                        u=Uri.fromFile(new File(headPath));
                    }

                    cropImageUri(u,CROP_REQUEST_CODE);
                    break;
                case CAMERA_REQUEST_CODE:
                    if(Build.VERSION.SDK_INT>=24){
                        u= FileProvider.getUriForFile(register_step_four_Activity.this,
                                "onlyid",new File(headPath));
                    }else {
                        u=Uri.fromFile(new File(headPath));
                    }
                    cropImageUri(u,CROP_REQUEST_CODE);
                    break;
                case CROP_REQUEST_CODE:
                    //显示裁剪后的图片
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        cropHeadBitmap = extras.getParcelable("data");
                        roundImageHead.setBackground(null);
                        roundImageHead.setImageBitmap(cropHeadBitmap);
                        falgHead=true;
                        if(falgHead==true&&flagSex==true&&flagBirth==true){
                            button_submit.setBackgroundColor(Color.parseColor("#12B7F5"));
                        }
                    }
            }
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        if (checkedId==radioButton_female.getId()){
            sex=0;
            roundImageHead.setBackgroundResource(R.drawable.default_female_img);
            radioButton_female.setTextColor(Color.parseColor("#333333"));
            radioButton_male.setTextColor(Color.parseColor("#cccccc"));
        }else if (checkedId==radioButton_male.getId()){
            sex=1;
            roundImageHead.setBackgroundResource(R.drawable.default_male_img);
            radioButton_female.setTextColor(Color.parseColor("#cccccc"));
            radioButton_male.setTextColor(Color.parseColor("#333333"));
        }
        flagSex=true;
        if(falgHead==true&&flagSex==true&&flagBirth==true){
            button_submit.setBackgroundColor(Color.parseColor("#12B7F5"));
        }
    }

    private void InitView(){

        button_submit=(Button)findViewById(R.id.btn_submit);
        roundImageHead=(RoundedImageView)findViewById(R.id.img_roudhead);
        radioButton_female=(RadioButton)findViewById(R.id.rbtn_female);
        radioButton_male=(RadioButton)findViewById(R.id.rbtn_male);
        radioGroup_sex=(RadioGroup)findViewById(R.id.radioGroupID);
        textView_birth=(TextView)findViewById(R.id.tv_bitrh);
        button_select_birth=(Button)findViewById(R.id.btn_select_birth);
        progressBar_register=(ProgressBar)findViewById(R.id.prg_register);

        progressBar_register.setVisibility(View.INVISIBLE); //设置不可见
        //设置监听

        button_submit.setOnClickListener(this);
        roundImageHead.setOnTouchListener(this);
        radioGroup_sex.setOnCheckedChangeListener(this);
        button_select_birth.setOnClickListener(this);
    }
    //打开相册
    private void openAlbum(){
        Intent intent=new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,IMAGE_REQUEST_CODE);
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data){
        String imagePath=null;
        Uri uri=data.getData();
        String a=uri.getAuthority();
        if(DocumentsContract.isDocumentUri(this,uri)){
            //如果是documents类型的uri，则通过document id处理
            String docId=DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id =docId.split(":")[1];  //解析出数字格式的id
                String selection= MediaStore.Images.Media._ID+"="+id;
                imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(docId));
            }
        }else if("content".equalsIgnoreCase(uri.getScheme())){
            //如果是content类型的uri，则使用普通方式处理
            imagePath=getImagePath(uri,null);
        }else if("file".equalsIgnoreCase(uri.getScheme())){
            //如果是file类型的uri，直接获取图片路径即可
            imagePath=uri.getPath();
        }

        //根据图片路径显示图片
        headPath=imagePath;
        //displayImage(imagePath);
    }



    private void handleImageBeforeKitKat(Intent data){
        Uri uri=data.getData();
        String imagePath=getImagePath(uri,null);
        headPath=imagePath;
        //displayImage(imagePath);
    }
    private String getImagePath(Uri uri,String selection){
        String path=null;
        //通过uri和selection来获取真实的图片路径
        Cursor cursor=getContentResolver().query(uri,null,selection,null,null);
        if(cursor!=null){
            if(cursor.moveToFirst()){
                path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
    //压缩后展示
    private void displayImage(String imagePath){
        if(imagePath!=null){

            Bitmap bitmap=BitmapFactory.decodeFile(imagePath);
            bitmap=compressImageFromFile(imagePath);
            //mImageHeader.setImageBitmap(bitmap);

        }else{
            Toast.makeText(this,"failed to get image",Toast.LENGTH_LONG).show();
        }
    }
    private void cropImageUri(Uri uri ,int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        //设置输入图片格式
        //intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("return-data", true);
        //是否关闭面部识别
        intent.putExtra("noFaceDetection", true); // no face detection
        //启动
        startActivityForResult(intent, requestCode);
    }
    private void DialogDismiss(){
        dialog.dismiss();
    }

    private View vBirthChoice;
    private boolean Leap=false;  //是否为闰年
    private Calendar c;
    private int tempBirthYear;
    private int tempBirthMonth;
    private int tempBirthDate;
    private void CreateBirthChoice(){
        AlertDialog.Builder builder7 = new AlertDialog.Builder(
                register_step_four_Activity.this);
       // builder7.setIcon(R.mipmap.ic_launcher);
        View view = LayoutInflater.from(register_step_four_Activity.this).inflate(
                R.layout.birth_choose, null);
        yearNumberPicker = (NumberPicker) view.findViewById(R.id.year_numberpicker);
        monthNumberPicker = (NumberPicker) view.findViewById(R.id.month_numberpicker);
        dateNumberPicker = (NumberPicker) view.findViewById(R.id.date_numberpicker);

        yearNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        monthNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        dateNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

        c = Calendar.getInstance();
        int maxYear = c.get(Calendar.YEAR);
        final int minYear=maxYear-120;
        yearNumberPicker.setMaxValue(maxYear);
        yearNumberPicker.setMinValue(minYear);
        yearNumberPicker.setValue(birthYear);
        monthNumberPicker.setMaxValue(12);
        monthNumberPicker.setMinValue(1);
        monthNumberPicker.setValue(birthMonth);
        dateNumberPicker.setMinValue(1);
        dateNumberPicker.setMaxValue(31);
        dateNumberPicker.setValue(birthDate);
        tempBirthYear=yearNumberPicker.getValue();
        tempBirthMonth=monthNumberPicker.getValue();
        tempBirthDate=dateNumberPicker.getValue();
        birthYear=yearNumberPicker.getValue();
        birthMonth=monthNumberPicker.getValue();
        birthDate=dateNumberPicker.getValue();

        //设置监听
        yearNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                tempBirthYear=yearNumberPicker.getValue();
                if(isLeapYear(tempBirthYear)) {
                    Leap = true;
                    if(monthNumberPicker.getValue()==2){
                        dateNumberPicker.setMaxValue(29);//如果是闰年
                    }
                }
                else
                    Leap=false;
                if(monthNumberPicker.getValue()==2){
                    dateNumberPicker.setMaxValue(28);//如果不是闰年
                }
            }
        });
        //设置监听
        monthNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                tempBirthMonth=monthNumberPicker.getValue();
                switch (tempBirthMonth){
                    case 1:
                    case 3:
                    case 5:
                    case 7:
                    case 8:
                    case 10:
                    case 12:
                        dateNumberPicker.setMaxValue(31);
                        break;
                    case 2:
                        if(Leap==true) dateNumberPicker.setMaxValue(29);//如果是闰年
                        else dateNumberPicker.setMaxValue(28);//如果不是闰年
                        break;
                    case 4:
                    case 6:
                    case 9:
                    case 11:
                        dateNumberPicker.setMaxValue(30);
                        break;
                }
            }
        });
        //设置监听
        dateNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                tempBirthDate=dateNumberPicker.getValue();
            }
        });



        builder7.setView(view);
        builder7.setPositiveButton("确定",
                new android.content.DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        birthYear=tempBirthYear;
                        birthMonth=tempBirthMonth;
                        birthDate=tempBirthDate;

                        age= c.get(Calendar.YEAR)-birthYear;
                        textView_birth.setText(" "+age+"岁");
                        textView_birth.setTextColor(Color.parseColor("#333333"));
                        textView_birth.setTextSize(17);
                        flagBirth=true;
                        if(falgHead==true&&flagSex==true&&flagBirth==true){
                            button_submit.setBackgroundColor(Color.parseColor("#12B7F5"));
                        }
                    }
                });
        builder7.setNegativeButton("取消",
                new android.content.DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        builder7.create();
        builder7.show();
    }

    //判断是否为闰年
    private boolean isLeapYear(int year){
        if((year%4==0&&year%100!=0)||year%400==0)
          return true;
      else
          return false;
    }

}
